package com.biz.hunter.webchat.controller;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.hunter.service.IEmployeeService;
import com.biz.hunter.service.IJobDescService;
import com.biz.hunter.service.impl.SysConfigService;
import com.biz.hunter.webchat.dto.TempRecuritDTO;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.util.DateUtil;
import com.biz.wechat.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("recurit")
public class RecuritController {
	private static final Logger logger = LoggerFactory
			.getLogger(RecuritController.class);

	@Autowired
	private IJobDescService jobService;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private IEmployeeService empService;
	@Autowired
	SurveyPersonDAO surveyPersonDAO;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private TempRecuritDAO tempRecuritDAO;

	@RequestMapping(value = "jobList.page", method = RequestMethod.GET)
	public String viewHotJob(HttpServletRequest request, ModelMap model) {
		int offset;
		String startStr = request.getParameter("offset");
		String selectParams = request.getParameter("selectParams");
		String domain = request.getParameter("domain");
        String city = request.getParameter("city");
		String companyName = request.getParameter("companyName");
		String companyBusiness = request.getParameter("companyBusiness");
		if (!StringUtils.isEmpty(companyName)) {
			selectParams = companyName;
		}
		if (StringUtils.isEmpty(startStr)) {
			offset = 0;
		} else {
			offset = Integer.valueOf(startStr);
		}

		List<TempRecurit> tempRecurits = tempRecuritDAO.selectList(selectParams, domain, city, offset, companyBusiness, 1000);
		List<TempRecuritDTO> dtos = new ArrayList<TempRecuritDTO>();
		if (!StringUtils.isEmpty(tempRecurits)) {
            for (TempRecurit tempRecurit: tempRecurits) {
                TempRecuritDTO dto = new TempRecuritDTO();
                BeanUtils.copyProperties(tempRecurit,dto);
                dto.setEndTime(formatTime(tempRecurit.getJobEndTime()));
                dto.setStartTime(formatTime(tempRecurit.getUpdateTime()));
                dtos.add(dto);
            }
        }
		model.addAttribute("jobs", dtos);

		// config
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);

		model.addAttribute("city", cityDAO.getALL());
		model.addAttribute("domain",domain);
		model.addAttribute("companyName", companyName);
		return "tempRecruit/hotJobList";
	}



    private String formatTime(Date jobEndTime) {
		if (jobEndTime != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(jobEndTime);
		}
		return "";
	}


	// 查看职位详情
	@RequestMapping(value = "jobDetail.page", method = RequestMethod.GET)
	public String viewJobDetail(HttpServletRequest request, int jobId,
			ModelMap model) {

		TempRecurit tempRecurit = tempRecuritDAO.selectById(jobId);
		TempRecuritDTO dto = new TempRecuritDTO();
		BeanUtils.copyProperties(tempRecurit,dto);
		dto.setEndTime(formatTime(tempRecurit.getJobEndTime()));
		model.addAttribute("job", dto);

		/* config */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);
		/**/
		return "tempRecruit/zhiweixinxi";
	}


//	@RequestMapping(value = "job/selfRecommend.page", method = RequestMethod.GET)
//	public String toSelfRecommend(HttpServletRequest request, ModelMap model) {
//		HttpSession session = request.getSession();
//
//	    String openid = (String)session.getAttribute("OpenId");
//	    logger.debug("openid is " + openid);
//	    if (!StringUtils.isEmpty(openid)) {
//	      model.addAttribute("openid", openid);
//	    }
//		return "tempRecruit/selfhouxuanren";
//	}
//
//	@RequestMapping(value = "job/otherRecommend.page", method = RequestMethod.GET)
//	public String toOtherRecommend(HttpServletRequest request, ModelMap model) {
//		HttpSession session = request.getSession();
//
//	    String openid = (String)session.getAttribute("OpenId");
//	    logger.debug("openid is " + openid);
//	    if (!StringUtils.isEmpty(openid)) {
//	      model.addAttribute("openid", openid);
//	    }
//		return "tempRecruit/houxuanren";
//	}

	// 职位分享页面
	@RequestMapping(value = "job/sharejob.page", method = RequestMethod.GET)
	public String sharejobPage(HttpServletRequest request, int jobid,
			ModelMap model) {

		HttpSession session = request.getSession();

		String openid = (String) session.getAttribute("OpenId");
		logger.debug("openid is " + openid);
		if (!StringUtils.isEmpty(openid)) {

			model.addAttribute("openid", openid);

			UserInfo user = userDAO.getByOpenId(openid);
			if (user != null) {

				Employee emp = empService.getByOpenId(openid);
				if (emp != null) {
					model.addAttribute("emp", emp);
				}

				JobDesc job = jobService.searchJobByID(jobid);
				if (job == null) {
					logger.info("invalid Job id " + jobid);
					model.addAttribute("msg", "该职位不存在或者已经过期。");
				}

				int companyId = job.getCompanyId();
				int cityId = job.getCityId();
				Company company = companyDAO.getById(companyId);
				City city = cityDAO.getById(cityId);

				Company expCompany = companyDAO.getById(job
						.getExpectcompanyid());

				job.setCity(city);
				job.setCompanyName(company.getName());
				long data = job.getExpiredDate();
				job.setExpiredDateStr(DateUtil.getDateStr(data));
				model.addAttribute("job", job);
				model.addAttribute("expcompany", expCompany);

				List<Company> companies = companyDAO.getALL();
				model.addAttribute("companies", companies);
			}

		}
		/* config */
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is "+ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {  
            url = url + "?" + request.getQueryString();  
        } 
		logger.debug("request url is " + url);
		
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		
		model.addAttribute("config", config);
		/**/
		return "tempRecruit/sharejobpage";
	}


}
